package com.Xht.www.servlet;

//后端响应客户拉黑商家的请求

import com.Xht.www.dao.UserBlacklistDAO;
import com.Xht.www.po.UserBlacklistPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@WebServlet("/blacklist")
public class BlacklistServlet extends HttpServlet {
    private UserBlacklistDAO blacklistDAO = new UserBlacklistDAO();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取参数
            Integer userId = Integer.parseInt(req.getParameter("userId"));
            String merchantName = req.getParameter("merchantName");
            String reason = req.getParameter("reason");

            // 验证参数
            if (userId == null || merchantName == null || reason == null) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write("{\"success\": false, \"message\": \"参数缺失\"}");
                return;
            }

            // 检查商家是否已经被该用户拉黑
            boolean isBlacklisted = checkIfMerchantBlacklisted(userId, merchantName);
            if (isBlacklisted) {
                resp.setStatus(HttpServletResponse.SC_CONFLICT);
                resp.getWriter().write("{\"success\": false, \"message\": \"该商家已被您拉黑\"}");
                return;
            }

            // 创建黑名单记录
            UserBlacklistPO blacklist = new UserBlacklistPO();
            blacklist.setUserId(userId);
            blacklist.setMerchantName(merchantName);
            blacklist.setBlacklistReason(reason);
            blacklist.setBlacklistTime(new Timestamp(new Date().getTime()));

            // 保存到数据库
            blacklistDAO.insertUserBlacklist(blacklist);

            // 返回成功响应
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write("{\"success\": true, \"message\": \"拉黑成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("{\"success\": false, \"message\": \"拉黑失败: " + e.getMessage() + "\"}");
        }
    }

    // 检查商家是否已经被该用户拉黑
    private boolean checkIfMerchantBlacklisted(int userId, String merchantName) {
        // 这里需要实现检查逻辑，可以在UserBlacklistDAO中添加相应方法
        UserBlacklistDAO dao = new UserBlacklistDAO();
        List<UserBlacklistPO> blacklists = dao.getUserBlacklistsByUserId(userId);
        for (UserBlacklistPO blacklist : blacklists) {
            if (blacklist.getMerchantName().equals(merchantName)) {
                return true;
            }
        }
        return false;
    }
}
